import { useMemoizedFn } from 'ahooks';
import { memo } from 'react';
import TextTip from '../TextTip';
import ImageBox from '../ImageBox';
import './index.less';

const TEXTS = {
    'image': '上传图片',
    'i-text': '修改文案'
};

const UploadBox = ({ onLoaded, data }) => {

    const handleUpload = useMemoizedFn((e) => {
        const file = e.target.files[0];
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function(e) {
            console.log(e.target);
            const img = new Image();
            img.onload = function() {
                console.log(img, file);
                onLoaded?.({
                    src: e.target.result,
                    width: img.width,
                    height: img.height,
                    naturalWidth: img.naturalWidth,
                    naturalHeight: img.naturalHeight,
                    ...file
                })
            }
            img.src = e.target.result;
            // console.log(files[0], e.target.result);
            // fabric.Image.fromURL(e.target.result, function(img) {
            //     console.log(img);
            // })
        }
    })

    const renderComponents = () => {
        const { type } = data;

        switch(type) {
            case 'image':
                return (
                    <>
                        <ImageBox data={data} />
                        <input style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }} type="file" accept="image/*" onChange={handleUpload} />
                    </>
                );
            case 'i-text':
                return <div className='i-text-container'>{data?.text || ''}</div>
            default:
                return null;
        }
    }

    if(!data.type) {
        return null;
    }

    return (
        <div className="upload-box-cotainer">
            <TextTip text={TEXTS[data.type]} />
            {
                renderComponents()
            }
        </div>
    )
}

export default memo(UploadBox);